package com.fjl.tomcat;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class TomcatApp1 {
    public static void main(String[] args) throws LifecycleException {
        Tomcat tomcat = new Tomcat();

        // 设置 Tomcat 基础目录
        tomcat.setBaseDir("tomcat");

        // 设置端口为 8080
        tomcat.setPort(8088);
        tomcat.getConnector();
        // 创建 Spring WebApplicationContext
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(WebAppConfig.class);  // WebConfig 是你的配置类，包含 @EnableWebMvc 和 @ComponentScan
        Context servletContext = tomcat.addContext("", null);
//        ctx.setServletContext((servletContext.getServletContext()));
//        ctx.refresh();
//        ctx.registerShutdownHook();
        // 创建 DispatcherServlet
        DispatcherServlet dispatcherServlet = new DispatcherServlet(ctx);
        //创建web容器上下文
        // 注册 DispatcherServlet
        Wrapper dispatcher = tomcat.addServlet(servletContext, "dispatcherServlet", dispatcherServlet);
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/*");


        // 启动 Tomcat
        tomcat.start();
        tomcat.getServer().await();
    }
}
